<?php
namespace app\api\controller\deerhome\user;

use app\api\controller\deerhome\user\Base;
use EasyWeChat\Kernel\Messages\Raw;
use think\Db;
use think\Log;
/**
 * 微信支付回调::储值卡充值
*/
class NotifyWallet extends Base
{
    public function index()
    {
        $_order_payed=false;
        $order_sn=$this->request->param("sn",'');
        $notifyCon=\WeChat\Contracts\Tools::getRawInput();
        if($notifyCon){
            Log::write('【微信支付-储值卡-回调】：'.json_encode($notifyCon));
        }
      
        if($order_sn=="" && $notifyCon=="" ){
            Log::error('【微信支付-储值卡-回调】订单号为空，且没有post数据');
            return;
        }
        $order=[];
        Db::startTrans();
        try {
            $config=$this->getWeixinConfig();
            $payment = \WePayV3\Order::instance($config);
            if($order_sn==""){
                $data = $payment->notify();
                $result=\json_decode($data['result'],true);
                $order_sn=$result['out_trade_no'];
            }
            $order_sn_mask=\explode("S",$order_sn);
            if(count($order_sn_mask)!=2){
                throw new \Exception("订单号格式不正确");
            }
            $order_sn_father=$order_sn_mask[0];
            $sub_order_id=(int)$order_sn_mask[1];

            $order=Db::name("deerhome_order_pay_log")->field("id,deerhome_user_id,type,is_wallet,status,price,give,payway_type")->where("id",$sub_order_id)->find();
            if(!$order){
                throw new \Exception("充值交易不存在");
            }
            if($order['status']!=1){
                throw new \Exception("该充值交易状态不可支付");
            }
            if($order['payway_type']!=1){
                throw new \Exception("该笔交易为线下交易");
            }
            $need_pay=$order['price'];
            $need_pay=$need_pay*100;
            $orderQuery=$payment->query($order_sn);
            if(!isset($orderQuery['trade_state'])){
                throw new \Exception("充值订单查询失败:".$orderQuery['message']);
            }
            if($orderQuery['trade_state']=="SUCCESS" ){
                if($orderQuery['amount']['payer_total']!=$need_pay){
                    throw new \Exception("充值订单支付金额不正确，应支付￥{$need_pay}分，实际支付￥{$orderQuery['amount']['payer_total']}分");
                }
            }else{
                throw new \Exception("充值订单交易状态[{$orderQuery['trade_state']}]");
            }

            $pay_time=date("Y-m-d H:i:s",strtotime($orderQuery['success_time']));
            $upateOrder=[];
            $upateOrder['status']=2;
            $upateOrder['pay_time']=$pay_time;
            $upateOrder['pay_way']='微信支付';
            $upateOrder['payway_type']=1;
            Db::name("deerhome_order_pay_log")->where("id",$sub_order_id)->update($upateOrder);

            //更新用户余额
            $money=bcadd($order['price'],$order['give'],2);
            Db::name("deerhome_user")->where("id",$order['deerhome_user_id'])->update([
                "wallet_charge"=>Db::raw("wallet_charge+{$money}")
            ]);

            Db::commit();
            echo '{"code","SUCCESS","msg":"OK"}}';
        } catch (\Exception $e) {
            echo '{"code","FAIL","msg":"'.$e->getLine()."|".$e->getMessage().'"}}';
            Log::error('【微信支付-储值卡-回调】充值'.$order_sn.'错误信息:'.$e->getLine()."|".$e->getMessage() );
        }
        //自动升级会员等级
        try{
            \Tools\UserAndAgentLev::actionUserById($order['deerhome_user_id']);
        }catch(\Exception $e){
        }
        return;
    }
}
?>